//
//  UITableView+.swift
//  SplendidSwift
//
//  Created by WY on 2021/1/8.
//

import UIKit

extension TypeWrapperProtocol where WrappedType : UITableView {
    
    /// 注册Cell
    public func registerCell<T: UITableViewCell>(_ type: T.Type) {
        let identifier = String(describing: type.self)
        wrappedValue.register(type, forCellReuseIdentifier: identifier)
    }
    
    /// 取重用Cell
    public func dequeueReusableCell<T: UITableViewCell>(_ type: T.Type) -> T {
        let identifier = String(describing: type.self)
        guard let cell = wrappedValue.dequeueReusableCell(withIdentifier: identifier) as? T else {
            fatalError("\(type.self) was not registered")
        }
        return cell
    }
    
    public func dequeueReusableCell<T: UITableViewCell>(_ type: T.Type, indexPath: IndexPath) -> T {
        let identifier = String(describing: type.self)
        guard let cell = wrappedValue.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? T else {
            fatalError("\(type.self) was not registered")
        }
        return cell
    }
    
    /// 根据View 获取对应Cell的indexpath
    public func indexPath(by child:UIView) -> IndexPath? {
        let point = child.convert(CGPoint.zero, to: wrappedValue)
        return wrappedValue.indexPathForRow(at: point)
    }
    
    /// 根据 child view  获取对应Cell
    public func cell(by child:UIView) -> UITableViewCell?{
        let point = child.convert(CGPoint.zero, to: wrappedValue)
        if let indexPath = wrappedValue.indexPathForRow(at: point) {
            return wrappedValue.cellForRow(at: indexPath)
        }
        return nil
    }
    
    public func reloadVisibleRows() {
        guard let rows = wrappedValue.indexPathsForVisibleRows else {
            return
        }
        UIView.performWithoutAnimation {
            wrappedValue.reloadRows(at: rows, with: .none)
        }
    }
}

